import type { RouteRecordRaw } from 'vue-router'

/*
 * @Date: 2025-07-19 01:20:31
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-11-17 00:26:13
 * @FilePath: /admin-vue/src/plugins/router/register.ts
 */
interface ViewModule {
  default?: {
    route?: Partial<RouteRecordRaw>
  }
}

// 使用 Record 类型来更明确地定义模块类型
type ModuleType = Record<string, () => Promise<{ default: ViewModule }>>

const layouts = import.meta.glob('@/layouts/*.vue') as ModuleType
const views = import.meta.glob('@/views/**/*.vue') as ModuleType

function getRoutes() {
  const layoutRoutes = [] as RouteRecordRaw[]
  for (const [file, module] of Object.entries(layouts)) {
    try {
      const route = getRouteByModule(file, module as ViewModule)
      const children = getChildrenRoutes(route)

      if (children.length > 0) {
        route.children = children
        route.redirect = children[0].path
        layoutRoutes.push(route)
      }
    } catch (error) {
      console.error(`Error processing route for ${file}:`, error)
    }
  }
  return layoutRoutes
}

//获取布局路由的子路由
function getChildrenRoutes(layoutRoute: RouteRecordRaw): RouteRecordRaw[] {
  if (!layoutRoute.name) {
    console.warn('Layout route missing name:', layoutRoute)
    return []
  }
  return Object.entries(views)
    .filter(
      ([file]) => file.includes(`/views/${String(layoutRoute.name)}`) && !file.includes('modules'),
    )
    .map(([file, module]) => getRouteByModule(file, module as ViewModule))
}

function getRouteByModule(file: string, module: ViewModule): RouteRecordRaw {
  const name = file
    .replace(/.+layouts\/|.+views\/|\.vue/gi, '')
    .replace(/\/index$/, '')
    .toLowerCase() // 统一转换为小写，避免大小写问题

  const route: RouteRecordRaw = {
    name: name.replace(/\//g, '.'),
    path: `/${name}`,
    component: module,
    meta: { title: name }, // 添加默认的 meta 信息
  }

  // 确保返回的类型符合 RouteRecordRaw
  const moduleRoute = module.default?.route || {}
  const mergedRoute = {
    ...route,
    ...moduleRoute,
    children: moduleRoute.children || undefined,
  } as RouteRecordRaw
  return mergedRoute
}

export default getRoutes
